import {
  addTestReport,
  delTestReport,
  queryTestReportList,
  updateTestReport,
} from "@/services/qualityTesting";
import { uploadUrl } from "@/untils";
import {
  DrawerForm,
  ProFormDatePicker,
  ProFormText,
  ProFormUploadButton,
  ProTable,
} from "@ant-design/pro-components";
import { Button, Form, message, Popconfirm } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { imgConfig } from "../PurchaseOrder";

const QualityTesting = () => {
  const actionRef: any = useRef(null);
  const { url } = imgConfig;
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<any>([]); //
  const [currentData, setCurrentData] = useState<any>(null);
  const [currentType, setCurrentType] = useState<string>("");
  const [open, setOpen] = useState(false);
  const toUrl = (e: string) => {
    window.open(url + e);
  };
  // 表格列配置
  const columns = [
    {
      title: "报告时间",
      dataIndex: "report_time",
      key: "report_time",
      width: 100,
      search: false,
    },
    {
      title: "创建日期",
      dataIndex: "create_time",
      key: "create_time",
      width: 120,
      render: (time: string) =>
        dayjs(Number(time) * 1000).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "文件",
      dataIndex: "file_route",
      key: "file_route",
      width: 120,
      search: false,
      render: (text: any) => {
        const list = text?.split(",");
        return (
          <>
            {list?.map((url: string) => (
              <div>
                <a onClick={() => toUrl(url)}>{url.replace("topic/", "")}</a>
              </div>
            ))}
          </>
        );
      },
    },
    {
      title: "操作",
      key: "action",
      width: 100,
      align: "center",
      search: false,
      render: (_: any, record: any) => (
        <>
          <a
            style={{ marginRight: 8 }}
            onClick={() => handleViewDetail(record)}
          >
            编辑
          </a>
          <Popconfirm
            title="提示"
            description="确认删除该记录吗？"
            onConfirm={() => handleDel(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const fetchData = async (params: any) => {
    const res = await queryTestReportList({
      page: 1,
      pagesize: 999,
    });
    return {
      data: res?.result?.data || [],
      total: res?.total || 0,
      success: true,
    };
  };

  const handleViewDetail = (record: any) => {
    setCurrentData(record);
    setOpen(true);
    setCurrentType("edit");
  };
  const handleDel = async (id: number) => {
    const res = await delTestReport({ id });
    if (res?.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
    } else {
      message.error("操作失败，请联系管理员");
    }
  };

  useEffect(() => {
    if (open && currentType === "edit") {
      const { report_time, id, file_route } = currentData;
      const list = file_route
        ? file_route?.split(",")?.map((url: string, i: number) => ({
            uid: `-${i}`,
            url,
            key: url,
            name: url,
            status: "done",
          }))
        : [];
      setFileList(list);
      form.setFieldsValue({
        id,
        report_time,
        pic: list,
      });
    }
  }, [currentType, open, currentData]);
  // 提交
  const handleSubmit = async (values: any) => {
    const { pic, report_time, id } = values;
    const pics = pic
      ?.filter((item: any) => {
        return item?.response?.success || item?.status === "done";
      })
      ?.map((item: any) => item?.response?.result?.savename || item?.url)
      ?.join(",")
      ?.replace(imgConfig?.url, "");
    if (!pics) {
      message.info("请先上传报告");
      return;
    }
    const res =
      currentType === "edit"
        ? await updateTestReport({
            id,
            report_time,
            pic: pics,
          })
        : await addTestReport({
            report_time,
            pic: pics,
          });
    if (res?.success) {
      message?.success(currentType === "edit" ? "编辑成功" : "新增成功");
      setOpen(false);
      actionRef?.current?.reload();
    } else {
      message.error("操作失败，请联系管理员");
    }
  };
  return (
    <>
      <ProTable
        actionRef={actionRef}
        columns={columns as any}
        request={fetchData}
        rowKey="id"
        search={false}
        pagination={{ pageSize: 10 }}
        options={false}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            onClick={() => {
              setOpen(true);
              setCurrentType("create");
            }}
          >
            新增质检直通率报告
          </Button>,
        ]}
      />
      <DrawerForm
        title={"新增质检直通率报告"}
        onFinish={handleSubmit}
        onOpenChange={(open) => {
          if (!open) {
            setCurrentData(null);
            setCurrentType("");
          }
        }}
        form={form}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setOpen(false),
        }}
        open={open}
      >
        <ProFormText name={"id"} hidden />
        <ProFormDatePicker.Month
          name="report_time"
          label="报告月份"
          width="md"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormUploadButton
          rules={[
            {
              required: true,
            },
          ]}
          fieldProps={{
            fileList,
            listType: "text",
            onChange: ({ fileList: newList }) => setFileList(newList),
          }}
          name="pic"
          label="上传报告"
          action={uploadUrl}
        />
      </DrawerForm>
    </>
  );
};

export default QualityTesting;
